import { LockOutlined, UserOutlined } from '@ant-design/icons';
import React from 'react';
import { connect } from 'umi';
import styles from '../index.less';
import { Alert } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { useModel } from '@umijs/max';
import { flushSync } from 'react-dom';
const LoginForm = (props) => {
  const { submitting, loginStatus, dispatch } = props;

  const { initialState, setInitialState } = useModel('@@initialState');
  const handleSubmit = (values) => {
    setInitialState({
      currentUser: { role: 'admin' },
    });
    dispatch({
      type: 'login/login',
      payload: { ...values },
    });
  };

  return (
    <ProForm
      submitter={{
        render: (_, dom) => dom.pop(),
        submitButtonProps: {
          loading: submitting,
          size: 'large',
          style: {
            width: '100%',
          },
        },
      }}
      isKeyPressSubmit={true}
      onFinish={async (values) => {
        handleSubmit(values);
      }}
    >
      {loginStatus && !loginStatus.success && loginStatus.message && !submitting && (
        <Alert style={{ marginBottom: 24 }} message={loginStatus.message} type="error" showIcon />
      )}
      <ProFormText
        name="username"
        fieldProps={{
          size: 'large',
          prefix: <UserOutlined className={styles.prefixIcon} />,
        }}
        placeholder="用户名"
        rules={[
          {
            required: true,
            message: '请输入用户名!',
          },
        ]}
      />
      <ProFormText.Password
        name="password"
        fieldProps={{
          size: 'large',
          prefix: <LockOutlined className={styles.prefixIcon} />,
        }}
        placeholder="密码"
        rules={[
          {
            required: true,
            message: '请输入密码',
          },
        ]}
      />
    </ProForm>
  );
};

export default connect(({ loading, login: { loginStatus } }) => ({
  submitting: loading.effects['login/login'],
  loginStatus,
}))(LoginForm);
